<?php
namespace Common\Controller;

use Think\Controller;
vendor('Aliyun.SignatureHelper');

class BaseController extends Controller
{
    const
        success_code = 200,
        error_code = 404;

    /**
     * 接口返回成功信息
     * @param $message
     * @param $content
     */
    public function successReturn($message="成功",$content=array()){
        $this->returnJson(self::success_code,$message,$content);
    }

    /**
     * 接口返回错误信息
     * @param $message
     */
    public function errorReturn($message="失败"){
        $this->returnJson(self::error_code,$message);
    }

    /**重写ajaxReturn方法
     * @param int $status
     * @param string $message
     * @param string $content
     */
    public function returnJson($status = 200, $message = '', $content = '')
    {
        $result['status'] = $status;
        $result['message'] = $message;
        if( $content == '' ){
            $result['content'] = (object)array();
        }else{
            $result['content'] = $content;
        }
        $this->ajaxReturn($result, 'json');
    }

    /**
     * 重写ajaxReturn方法，jsonp格式返回
     * @param int $code
     * @param string $message
     * @param string $content
     */
    public function returnJsonp($code = 200, $message = '', $content = '')
    {
        $result['status'] = $code;
        $result['message'] = $message;
        if( $content == '' ){
            $result['content'] = (object)array();
        }else{
            $result['content'] = $content;
        }
        $this->ajaxReturn($result, 'jsonp');
    }


    /*************** 互亿无线*****************/
    // 发送短消息
    public function send($phones, $msg, $send_date = '', $send_num = 1, $sms_type = '', $version = '1.0', &$sms_error = '') {
        $sms_name = C("sms_name"); //用户名
        $sms_password = C("sms_password"); //密码
        //function send($phones, $msg, &$sms_error = '') {
        /* 检查发送信息的合法性 */
        $contents = $this->get_contents($phones, $msg);
        if (!$contents) {
            return false;
        }

        /* 获取API URL */
        $sms_url = "http://106.ihuyi.com/webservice/sms.php?method=Submit";

        if (count($contents) > 1) {
            foreach ($contents as $key => $val) {
                $post_data = "account=" . $sms_name . "&password=" . $sms_password . "&mobile=" . $val['phones'] . "&content=" . rawurlencode($val['content']); //密码可以使用明文密码或使用32位MD5加密
                //$get = $this->Post($post_data, $sms_url);
                $get = Http::doPost($sms_url, $post_data);
                $gets = $this->xml_to_array($get);
                sleep(1);
            }
        } else {
            $post_data = "account=".$sms_name."&password=".$sms_password."&mobile=".$phones."&content=".rawurlencode("您的验证码是：".$msg."。请不要把验证码泄露给其他人。");
            //密码可以使用明文密码或使用32位MD5加密
            $get = $this->Post($post_data, $sms_url);
            $gets = $this->xml_to_array($get);
        }


        //print_r($gets);exit; //开启调试模式
        if ($gets['SubmitResult']['code'] == 2) {
            return true;
        } else {
            $sms_error = $gets['SubmitResult']['msg'];
            //$this->logResult($sms_error);
            return "发送失败";
        }
    }

    public function Post($curlPost, $url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    public function xml_to_array($xml) {
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if (preg_match_all($reg, $xml, $matches)) {
            $count = count($matches[0]);
            for ($i = 0; $i < $count; $i++) {
                $subxml = $matches[2][$i];
                $key = $matches[1][$i];
                if (preg_match($reg, $subxml)) {
                    $arr[$key] = $this->xml_to_array($subxml);
                } else {
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }

    //检查手机号和发送的内容并生成生成短信队列
    public function get_contents($phones, $msg) {
        if (empty($phones) || empty($msg)) {
            return false;
        }
        //$msg.='【'. $GLOBALS['_CFG']['shop_name'].'】'; //by wanganlin delete
        $phone_key = 0;
        $i = 0;
        $phones = explode(',', $phones);
        foreach ($phones as $key => $value) {
            if ($i < 200) {
                $i++;
            } else {
                $i = 0;
                $phone_key++;
            }
            if ($this->is_moblie($value)) {
                $phone[$phone_key][] = $value;
            } else {
                $i--;
            }
        }
        if (!empty($phone)) {
            foreach ($phone as $phone_key => $val) {

                $phone_array[$phone_key]['phones'] = implode(',', $val);
                $phone_array[$phone_key]['content'] = $msg;
            }
            return $phone_array;
        } else {
            return false;
        }
    }

    // 自动转换字符集 支持数组转换
    public function auto_charset($fContents, $from = 'gbk', $to = 'utf-8') {
        $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
        $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
        if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
            //如果编码相同或者非字符串标量则不转换
            return $fContents;
        }
        if (is_string($fContents)) {
            if (function_exists('mb_convert_encoding')) {
                return mb_convert_encoding($fContents, $to, $from);
            } elseif (function_exists('iconv')) {
                return iconv($from, $to, $fContents);
            } else {
                return $fContents;
            }
        } elseif (is_array($fContents)) {
            foreach ($fContents as $key => $val) {
                $_key = auto_charset($key, $from, $to);
                $fContents[$_key] = auto_charset($val, $from, $to);
                if ($key != $_key)
                    unset($fContents[$key]);
            }
            return $fContents;
        }
        else {
            return $fContents;
        }
    }

    // 检测手机号码是否正确
    public function is_moblie($moblie) {
        return preg_match("/^0?1((3|7|8)[0-9]|5[0-35-9]|4[57])\d{8}$/", $moblie);
    }

    //打印日志
    public function logResult($word = '') {
        $fp = fopen(ROOT_PATH . "data/smserrlog.txt", "a");
        flock($fp, LOCK_EX);
        fwrite($fp, "执行日期：" . strftime("%Y%m%d%H%M%S", time()) . "\n" . $word . "\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
    /***************END 互亿无线*****************/


    /*************** 阿里云短信 *****************/
    /**
     * 发送短信
     * @param $phone            手机号码
     * @param $sms_mod          短信模板,1 验证码，2 下单成功， 3 接单员新订单， 4 完成订单
     * @param string $yzm       验证码
     * @return bool|\stdClass
     */
    function sendSms($phone,$sms_mod,$yzm='') {
        //判断使用的短信模板
        switch ($sms_mod){
            case 1:
                $TemplateCode = 'SMS_136470008';//验证码模板
                break;
            case 2:
                $TemplateCode = 'SMS_136386385';//下单成功模板
                break;
            case 3:
                $TemplateCode = 'SMS_136386322';//接单员新订单模板
                break;
            case 4:
                $TemplateCode = 'SMS_136391308';//完成订单模板
                break;
        }

        $params = array ();

        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = "LTAIQ6LQQvNmZlHf";
        $accessKeySecret = "u097azkeZdD6MKJr9hknOikumVVloy";

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $phone;

        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = "同城帮续签";

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $TemplateCode;

        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        if($sms_mod == 1) {
            $params['TemplateParam'] = Array(
                "code" => $yzm
            );
        }
//
//        // fixme 可选: 设置发送短信流水号
//        $params['OutId'] = "12345";
//
//        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
//        $params['SmsUpExtendCode'] = "1234567";


        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new \SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $accessKeyId,
            $accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        // fixme 选填: 启用https
        // ,true
        );

        return $content;
    }
    /*************** END 阿里云短信 *****************/

    /********** DataTable处理方法 **************/
    /**
     * 返回数据到前端DataTable
     * @by JYuan
     * @param $list_data
     * @param $order
     * @param $count
     * @param $draw
     */
    public function dataTableReturnJson($list_data,$order,$count,$draw){
        $output = array(
            "data" => $list_data,
            "order" => $order,
            "recordsTotal" => $count,       //总数目
            "recordsFiltered" => $count,    //过滤数目
            "draw" => intval($draw)
        );
        $this->ajaxreturn($output,'json');
    }

    /**
     * 处理前端DataTable传入的字段数据
     * @by JYuan
     * @param $columns 前端传入的列数据
     * @return string 前端需要的列名数据
     */
    public function getDtFieldData($columns){
        $field = "";
        for($i = 0;$i < count($columns);$i++) {
            if($columns[$i]['name'] == "") continue;
            if ($field == "") {
                $field = $columns[$i]['name'];
            } else {
                $field .= "," . $columns[$i]['name'];
            }
        }
        return $field;
    }

    /**
     * * 处理前端DataTable传入的排序数据
     * @by JYuan
     * @param $columns
     * @param $order_input
     * @return string
     */
    public function getDtOrderData($columns,$order_input){
        $order = "";
        foreach($order_input as $key=>$value){
            if($order == ""){
                $order = $columns[$value['column']]['data'].' '.$value['dir'];
            } else{
                $order .= ",".$columns[$value['column']]['data'].' '.$value['dir'];
            }
        }
        return $order;
    }
    /********** END DataTable处理方法 **************/

    /**
     * 上传图片方法
     * @param $file_content
     * @param string $rootPath
     * @param string $savePath
     * @param $saveName
     * @return array
     */
    public function uploadImageFileAction($file_content,$rootPath="./Public/Remark/",$savePath="",$saveName){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 31457280000;// 设置附件上传大小
        $upload->exts = array('jpg', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = $rootPath; // 设置附件上传根目录
        $upload->savePath = $savePath;
        $upload->saveName = $saveName;
        $upload->replace = true;
        $upload->autoSub = false;
        // 上传单个文件
        $info = $upload->uploadOne($file_content);

        if(!$info) {// 上传错误提示错误信息
            //addFileLog(json_encode($info));
            return ["code"=>0,"content"=>$upload->getError()];
        }else{// 上传成功 获取上传文件信息
            return ["code"=>1,"content"=>$rootPath.$savePath.$info['savename']];
        }
    }

    /**
     * 上传图片压缩方法
     * @param $file_content
     * @param string $rootPath
     * @param string $savePath
     * @param $saveName
     * @return array
     */
    public function uploadImageFileCompressAction($file_content,$rootPath="./Public/Remark/",$savePath="",$saveName){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 31457280000;// 设置附件上传大小
        $upload->exts = array('jpg', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath = $rootPath; // 设置附件上传根目录
        $upload->savePath = $savePath;
        $upload->saveName = $saveName;
        $upload->replace = true;
        $upload->autoSub = false;
        // 上传单个文件
        $info = $upload->uploadOne($file_content);
        if(!$info) {// 上传错误提示错误信息
            //addFileLog(json_encode($info));
            return ["code"=>0,"content"=>$upload->getError()];
        }else{// 上传成功 获取上传文件信息
            //addFileLog(json_encode($file_content));
            //原图地址
            $original_address = $rootPath.$savePath.$info['savename'];
            if($file_content['size'] > 1048576){//大于1MB进行压缩
                //压缩图片
                $str = strrchr($file_content['name'],".");
                $file_type = substr($str,1,strlen($str));
                $image = new \Think\Image();
                $image->open($original_address);
                $file_name = time().rand(1000,9999);
                //压缩后地址
                $compress_address = $rootPath.$savePath.$file_name.".".$file_type;
                $image->thumb(($image->width()*0.4),($image->height()*0.4),\Think\Image::IMAGE_THUMB_FILLED)->save($compress_address);
                unlink($original_address);
                unset($image);
                return ["code"=>1,"content"=>$compress_address];
            }else{
                return ["code"=>1,"content"=>$original_address];
            }
        }
    }

    /**
     * 上传excel文件方法
     * @by JYuan
     * @param $file_content
     * @param string $rootPath
     * @param string $savePath
     * @param $saveName
     * @return bool|string
     */
    public function uploadExcelFileAction($file_content,$rootPath="./Public/Remark/",$savePath="",$saveName){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 31457280;// 设置附件上传大小
        $upload->exts = array('xls', 'xlsx');// 设置附件上传类型
        $upload->rootPath = $rootPath; // 设置附件上传根目录
        $upload->savePath = $savePath;
        $upload->saveName = $saveName;
        $upload->replace = true;
        $upload->autoSub = false;
        // 上传单个文件
        $info = $upload->uploadOne($file_content);

        if(!$info) {// 上传错误提示错误信息
            //addFileLog(json_encode($info));
            return false;
        }else{// 上传成功 获取上传文件信息
            $str = strrchr($file_content['name'],".");
            $file_type = substr($str,1,strlen($str));
            return "/Public/".$savePath.$saveName.".".$file_type;
        }
    }

    /**
     * 导入xls文件数据
     * @by JYuan
     * @param $field
     * @return bool
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public function uploadExcel($field){
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.IOFactory');
        Vendor('PHPExcel.PHPExcel.Reader.Excel5');
        //以上三步加载phpExcel的类

        $objReader = \PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format
        //接收存在缓存中的excel表格
        $filename = $field['tmp_name'];
        $objPHPExcel = $objReader->load($filename); //$filename可以是上传的表格，或者是指定的表格
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        // $highestColumn = $sheet->getHighestColumn(); // 取得总列数

        //循环读取excel表格,读取一条,插入一条
        //j表示从哪一行开始读取  从第二行开始读取，因为第一行是标题不保存
        //$a表示列号
        for($j=2;$j<=$highestRow;$j++)
        {
            $input_array = array();
            $input_array['name'] = $objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();//获取A(业主名字)列的值
            $input_array['phone'] = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//获取B(密码)列的值

            $check_phone_result = M("User")
                ->where("phone = '".$input_array['phone']."'")
                ->find();
            if($check_phone_result){
                continue;
            }

            $input_array['type'] = 1;
            $input_array['c_time'] = time();
            M("User")->add($input_array);
        }
        return true;
    }

    /**
     * 获取小程序AccessToken
     * @return mixed
     */
    public function getWxAppAccessToken(){
        $wx_app_access_token = S("wx_app_access_token");
        if($wx_app_access_token){
            return $wx_app_access_token;
        }else{
            vendor('WechatApi.WxAppApi');
            $wx_api = new \WxAppApi();
            $result = $wx_api->getWxAppAccessToken();
            //使改缓存提前10秒钟过期
            S("wx_app_access_token",$result['access_token'],$result['expires_in']);
            unset($wx_api);
            return $result['access_token'];
        }
    }
}